<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目标段" prop="institutionCode">
        <el-select
          v-model="queryParams.institutionCode"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleBidChange"
        >
          <el-option-group
            v-for="group in projectBidOptions"
            :key="group.name"
            :label="group.name">
            <el-option
              v-for="item in group.bids"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supervisor:meterage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supervisor:meterage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supervisor:meterage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="single"
          @click="handleDelivery"
          v-hasPermi="['supervisor:meterage:delivery']"
        >传送</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-lock"
          size="mini"
          :disabled="multiple"
          @click="handleLock"
          v-hasPermi="['supervisor:meterage:lock']"
        >锁定</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleSummary"
          v-hasPermi="['supervisor:meterage:summary']"
        >汇总</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="meterageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
      <el-table-column label="项目名称" align="center" prop="projectName" width="150" />
      <el-table-column label="单位" align="center" prop="companyName" width="200" show-overflow-tooltip />
      <el-table-column label="标段" align="center" prop="institutionName" width="150" />
      <el-table-column label="期次" align="center" prop="periodName" width="80" />
      <el-table-column label="申请编号" align="center" prop="applyCode" />
<!--      <el-table-column label="当前部门" align="center" prop="currentDeptName" />-->
      <el-table-column label="当前用户" align="center" prop="currentUserName" />
      <el-table-column label="是否锁定" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_string_yes_no" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-picture"
            type="primary"
            size="small"
            v-if="scope.row.annexCount > 0"
            @click="handleAnnex(scope.row)">
          </el-button>
          <el-button
            icon="el-icon-picture-outline"
            size="small"
            v-if="scope.row.annexCount == 0"
            @click="handleAnnex(scope.row)">
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-grid"
            @click="handleDetail(scope.row)"
          >计量详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-unlock"
            @click="handleUnlock(scope.row)"
            v-if="scope.row.status == '1'"
            v-hasPermi="['supervisor:meterage:unlock']"
          >解锁</el-button>
        </template>
      </el-table-column>
      <el-table-column label="流程图" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            @click="handleWorkflow(scope.row)"
          >流程图</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监理计量对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目标段" prop="institutionCode" label-width="100px">
          <el-select v-model="form.institutionCode" placeholder="请选择项目标段" style="width: 100%" @change="selectBidOnChange">
            <el-option
              v-for="item in bidOptions"
              :key="item.institutionCode"
              :label="item.institutionName"
              :value="item.institutionCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="期　　次" prop="periodName" label-width="100px">
          <el-select v-model="form.periodName" placeholder="请选择期次" style="width: 100%">
            <el-option
              v-for="item in periodOptions"
              :key="item.periodName"
              :label="item.periodName"
              :value="item.periodName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请编号" prop="applyCode" label-width="100px">
          <el-input v-model="form.applyCode" placeholder="请输入申请编号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 传送对话框 -->
    <el-dialog :title="delivery.title" :visible.sync="delivery.open" :close-on-click-modal="false" width="700px" style="margin-top: 150px" append-to-body>
      <el-form ref="deliveryForm" :model="deliveryForm" :rules="deliveryRules" label-width="80px">
        <el-divider content-position="left"><i class="el-icon-s-operation"></i>选择节点</el-divider>
        <el-form-item label="" prop="workflowNodeUuid" label-width="100px">
          <el-radio-group v-model="deliveryForm.workflowNodeUuid" @change="deliveryNodeChange">
            <el-radio style="width: 100px"
                      v-for="item in deliveryNodeOptions"
                      :key="item.workflowNodeUuid"
                      :label="item.workflowNodeUuid"
            >{{item.workflowNodeName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-divider content-position="left"><i class="el-icon-user-solid"></i>选择用户</el-divider>
        <el-form-item label="" prop="user" label-width="100px">
          <el-radio-group v-model="deliveryForm.user">
            <el-radio style="width: 100px"
                      v-for="item in deliveryNodeUserOptions"
                      :key="item.userName"
                      :label="item.userName"
            >{{item.nickName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-divider content-position="left"><i class="el-icon-s-order"></i>备注信息</el-divider>
        <el-input v-model="deliveryForm.reason" type="textarea"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deliverySubmitForm">确 定</el-button>
        <el-button @click="deliveryCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 汇总对话框 -->
    <el-dialog :title="summary.title" :visible.sync="summary.open" :close-on-click-modal="false" width="900px" style="margin-top: 150px" append-to-body>
      <div class="app-container">
        <el-form ref="summaryForm" :model="summaryForm" :rules="summaryRules" label-width="80px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="项目标段" prop="institutionCode" label-width="100px">
                <el-select v-model="summaryForm.institutionCode" placeholder="请选择" style="width: 100%" @change="selectSummaryBidOnChange">
                  <el-option
                    v-for="item in summary.bidOptions"
                    :key="item.institutionCode"
                    :label="item.institutionName"
                    :value="item.institutionCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="期　　次" prop="periodName" label-width="100px">
                <el-select v-model="summaryForm.periodName" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="item in summary.periodOptions"
                    :key="item.periodName"
                    :label="item.periodName"
                    :value="item.periodName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否批复" prop="isApprove" label-width="100px" v-hasPermi="['supervisor:meterage:summary:approve']">
                <el-select v-model="summaryForm.isApprove" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="item in summary.approveOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-divider content-position="left">说明</el-divider>
            <div class="body" style="margin-left: 40px">
              <p>
                <el-badge :value="1" class="item" type="primary">
                </el-badge>
                用户类型只有属于驻地、监理、总监、业主类型才能使用数据汇总功能。
              </p>
              <p>
                <el-badge :value="2" class="item" type="primary">
                </el-badge>
                各级用户不能在本期工程计量数据为空的情况下进行数据汇总。
              </p>
              <p>
                <el-badge :value="3" class="item" type="primary">
                </el-badge>
                若某一标段在某一期未进行工程计量，当期需要进行空计量的时候，只需要业主用户直接进行批复数据汇总操作。
              </p>
              <p>
                <el-badge :value="4" class="item" type="primary">
                </el-badge>
                除第一期汇总外，只有上一期数据由业主批复汇总后，方能进行本期数据汇总。
              </p>
              <p>
                <el-badge :value="5" class="item" type="primary">
                </el-badge>
                只有业主用户具有数据汇总批复权限，数据汇总批复后，本期进入锁定状态，将不能进行监理计量操作。
              </p>
              <p>
                <el-badge :value="6" class="item" type="primary">
                </el-badge>
                如果发现本期计量数据有误，并且已由业主用户批复锁定，请及时联系业主用户，将数据进行未批复汇总操作，监理计量数据退回至填报单位进行修改。
              </p>

            </div>
          </el-row>

          <el-row type="flex" justify="center" align="middle">
            <el-button type="primary" style="width: 150px;height: 80px;font-size: 28px" @click="summarySubmitForm">数据汇总</el-button>
          </el-row>

        </el-form>
      </div>

    </el-dialog>

    <workflow ref="workflow" :uuid="uuid" ></workflow>

    <annex ref="annex"></annex>

  </div>
</template>

<script>
import { listMeterage, getMeterage, delMeterage, addMeterage, updateMeterage, beforeAddValidate, delivery, lock, unlock } from "@/api/supervisor/meterage";
import { selectProjectSupervisorBid, dropdownSupervisorBid} from "@/api/project/bid";
import { selectPeriodList } from "@/api/supervisor/period";
import { getWorkflowNode, getWorkflowNodeUser} from "@/api/common/workflow";
import { getMessageCount } from "@/api/common/message";
import workflow from "@/views/common/workflow/workflow";
import annex from "@/views/common/annex/annex";
import { beforeSummaryValidate, init, summary} from "@/api/supervisor/summary";
import { dropDownSummaryPeriodList } from "@/api/supervisor/period";

export default {
  name: "Meterage",
  dicts: ['sys_string_yes_no'],
  components: { workflow, annex },
  data() {
    return {
      // 标段下拉框
      projectBidOptions: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监理计量表格数据
      meterageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 传送参数
      delivery: {
        title: "",
        open: false
      },
      deliveryNodeOptions: [],
      deliveryNodeUserOptions: [],
      deliveryForm: {},
      deliveryRules: {
        institutionCode: [
          { required: true, message: "项目标段不能为空", trigger: "blur" }
        ],
        periodName: [
          { required: true, message: "工期不能为空", trigger: "blur" }
        ],
      },
      // 汇总参数
      summary: {
        // 标题
        title: "",
        // 是否打开窗口
        open: false,
        // 汇总标段下拉框数据
        bidOptions: [],
        // 汇总工期下拉框数据
        periodOptions: [],
        // 是否批复
        approveOptions: [{
          value: 'N',
          label: '未批复'
        }, {
          value: 'Y',
          label: '批复'
        }]
      },
      summaryForm: {},
      summaryRules: {
        institutionCode: [
          {required: true, message: "项目标段不能为空", trigger: "blur" }
        ],
        periodName: [
          { required: true, message: "工期不能为空", trigger: "blur" }
        ],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        institutionCode: [
          {required: true, message: "项目标段不能为空", trigger: "blur" }
        ],
        periodName: [
          { required: true, message: "工期不能为空", trigger: "blur" }
        ],
        applyCode: [
          { pattern: /^[a-zA-Z0-9_-]{0,}$/, message: "申请编号不能包含中文或特殊符号", trigger: "blur" },
          { required: true, message: "申请编号不能为空", trigger: "blur" },
          { max: 50, message: '申请编号最大长度为50个字符', trigger: 'blur'}
        ]
      },
      // 新增标段下拉框
      bidOptions:[],
      // 新增工期下拉框
      periodOptions: [],
      // uuid
      uuid: null
    };
  },
  created() {
    this.getList();
    this.initBidSelect();
  },
  methods: {
    /** 非当前用户不能进行编辑和删除操作 */
    checkSelectable(row) {
      return this.isRowEdit(row);
    },
    // 是否可以编辑
    isRowEdit(row) {
      // 获取当前用户名
      let loginName = this.$store.state.user.name;
      let userName = row.currentUser;
      if (loginName == userName && row.status != 1) {
        return true;
      } else {
        return false;
      }
    },
    /** 初始化标段下拉框 */
    initBidSelect() {
      selectProjectSupervisorBid().then(response => {
        this.projectBidOptions = response.data;
      });
    },
    /** 查询监理计量列表 */
    getList() {
      this.loading = true;
      listMeterage(this.queryParams).then(response => {
        this.meterageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 标段下拉框发生变化
    handleBidChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        masterId: null,
        institutionCode: null,
        institutionName: null,
        periodName: null,
        projectId: null,
        projectName: null,
        companyName: null,
        applyCode: null,
        currentDept: null,
        currentDeptName: null,
        currentUser: null,
        currentUserName: null,
        status: "0",
        uuid: null,
        workflowUuid: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 传送表单重置
    deliveryReset() {
      this.deliveryForm = {
        taskUuid: null,
        workflowUuid: null,
        user: null,
        reason: null
      };
      this.deliveryNodeOptions = [];
      this.deliveryNodeUserOptions = [];
    },
    // 汇总表单重置
    summaryReset() {
      this.summaryForm = {
        institutionCode: null,
        periodName: null,
        isApprove: "N",
      };
      this.summaryForm.bidOptions = [];
      this.summaryForm.periodOptions = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.masterId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 项目标段下拉框发生改变事件 */
    selectBidOnChange() {
      this.form.periodName = null;
      this.selectPeriodList();
    },
    /** 获取工期下拉框 */
    selectPeriodList() {
      selectPeriodList({institutionCode: this.form.institutionCode}).then(response => {
        this.periodOptions = response.data;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      beforeAddValidate().then(response => {
        this.reset();
        this.open = true;
        this.title = "添加监理计量";
        dropdownSupervisorBid().then(response => {
          this.bidOptions = response.data;
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const masterId = row.masterId || this.ids
      getMeterage(masterId).then(response => {
        dropdownSupervisorBid().then(response => {
          this.bidOptions = response.data;
        });
        selectPeriodList({institutionCode: response.data.institutionCode}).then(response => {
          this.periodOptions = response.data;
        });
        this.form = response.data;
        this.open = true;
        this.title = "修改监理计量";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.masterId != null) {
            updateMeterage(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMeterage(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const masterIds = row.masterId || this.ids;
      this.$modal.confirm('是否确认删除选中的数据项？').then(function() {
        return delMeterage(masterIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 监理计量详情按钮操作 */
    handleDetail(row) {
      this.$router.push({ path: '/supervisor/meterage/detail/index/' + row.masterId, query: { masterId: row.masterId, uuid: row.uuid, status: row.status} })
    },
    /** 传送按钮操作 */
    handleDelivery(row) {
      this.deliveryReset();
      const masterId = row.masterId || this.ids[0];
      getMeterage(masterId).then(response => {
        const uuid = response.data.uuid;
        this.deliveryForm.taskUuid = uuid;
        getWorkflowNode({taskUuid: uuid}).then(response => {
          this.deliveryNodeOptions = response.nodes;
          this.delivery.title = "数据传送";
          this.delivery.open = true;
        });
      });
    },
    // 传送部门发生改变事件
    deliveryNodeChange(val) {
      getWorkflowNodeUser({taskUuid: this.deliveryForm.taskUuid, workflowNodeUuid: val}).then(response => {
        this.deliveryNodeUserOptions = response.users;
        this.deliveryForm.user = null;
      });
    },
    // 传送对话框取消按钮
    deliveryCancel() {
      this.delivery.open = false;
      this.deliveryReset();
    },
    /** 提交按钮 */
    deliverySubmitForm() {
      this.$refs["deliveryForm"].validate(valid => {
        if (valid) {
          this.$loading({
            lock: true,
            text: '数据传送中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          // 监理计量传送
          delivery(this.deliveryForm).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.delivery.open = false;
            this.getList();
            this.$loading().close();
            this.deliveryReset();
            getMessageCount().then(response => {
              this.$store.commit("SET_MESSAGE_COUNT", response.messageCount);
            });
          }).catch(() => {
            this.$loading().close();
          });
        }
      });
    },
    /** 流程图按钮操作 */
    handleWorkflow(row) {
      this.$refs.workflow.show(row.uuid);
    },
    /** 附件按钮操作 */
    handleAnnex(row) {
      this.$refs.annex.show(row.uuid, 3, this.isRowEdit(row));
    },
    /** 锁定按钮操作 */
    handleLock(row) {
      const masterId = row.masterId || this.ids;
      this.$modal.confirm('确认锁定选中的数据项？').then(function() {
        return lock(masterId);
      }).then(() => {
        this.getList();
        getMessageCount().then(response => {
          this.$store.commit("SET_MESSAGE_COUNT", response.messageCount);
        });
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 解锁按钮操作 */
    handleUnlock(row) {
      this.reset();
      const masterId = row.masterId || this.ids
      this.$modal.confirm('确认解锁选中的数据项？').then(function() {
        return unlock(masterId);
      }).then(() => {
        this.getList();
        getMessageCount().then(response => {
          this.$store.commit("SET_MESSAGE_COUNT", response.messageCount);
        });
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 汇总按钮操作 */
    handleSummary() {
      this.summaryReset();
      beforeSummaryValidate().then(response => {
        this.summaryInit();
      });
    },
    // 汇总初始化
    summaryInit() {
      init().then(response => {
        this.summary.bidOptions = response.bids;
        this.summary.periodOptions = response.periods;
        this.summaryForm.institutionCode = response.institutionCode;
        this.summaryForm.periodName = response.periodName;
        this.summary.title = "数据汇总";
        this.summary.open = true;
      });
    },
    /** 汇总项目标段下拉框发生改变事件 */
    selectSummaryBidOnChange() {
      this.summaryForm.periodName = null;
      this.summary.periodOptions = [];
      this.selectSummaryPeriodList();
    },
    /** 获取工期下拉框 */
    selectSummaryPeriodList() {
      dropDownSummaryPeriodList({institutionCode: this.summaryForm.institutionCode}).then(response => {
        this.summary.periodOptions = response.periods;
        this.summaryForm.periodName = response.periodName;
      });
    },
    /** 汇总提交按钮 */
    summarySubmitForm() {
      this.$refs["summaryForm"].validate(valid => {
        console.log(this.summaryForm.institutionCode);
        console.log(this.summaryForm.periodName);
        console.log(valid);
        if (valid) {
          // 数据汇总
          const loading = this.$loading({
            lock: true,
            text: '数据汇总中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          summary(this.summaryForm).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.summary.open = false;
            loading.close();
          }).catch(() => {
            loading.close();
          });
        }
      });
    }
  }
};
</script>
